#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
import time
import json
from datetime import datetime, timedelta

def newrankXhs(cookie,token,difyheaders,dataset_id,document_id,this_date):
    headers = {
        'Content-Type': 'application/json',
        'n-token': token,
        'cookie': cookie,
    }
    response = requests.post('https://gw.newrank.cn/api/nrnavigation/nr/navigation/hotSpot/list', headers=headers)

    if response.status_code != 200:
        return "failure"
    else:
        platform_map = {
            1: "快手热点",
            2: "抖音热点",
            5: "微博热点",
            6: "小红书热点",
            7: "百度热点",
            8: "B站热点",
            9: "知乎热点",
            10: "头条热点"
        }
        print("http newrank is ok.....")
        json_data = response.json()
        original_list = json_data['data']
        for item in original_list:
            # 提取热点内容信息
            nrAppHotSpotRankDtoList = item.get('nrAppHotSpotRankDtoList', [])
            # 重新组装热点数据
            hot_spot_data = [
                {
                    "hotValue": item.get('hotValue'),
                    "content": item.get('sentence'),
                    "updateTime": item.get('updateTime')
                }
                for item in nrAppHotSpotRankDtoList
            ]
            # 获取平台类型
            play_type = item.get('playType')
            platform_name = platform_map.get(play_type, f'未知平台({play_type})') if play_type is not None else ''

            segmentcontent = {
                "keyword": this_date+str(platform_name),
                "content": hot_spot_data
            }
            # 将内容转换为字符串格式
            content_str = json.dumps(segmentcontent, ensure_ascii=False) if segmentcontent else ""
            segment = {
                "content": content_str,
                "keywords": [this_date+str(platform_name)]
            }
            segments_data = {
                "segments": [segment]
            }

            url = "http://localhost:8088/v1/datasets/"+dataset_id+"/documents/"+document_id+"/segments"
            post_with_detailed_retry(url, difyheaders, segments_data)
        return "ok"

def hotSpotIndex(cookie,token,difyheaders,dataset_id,document_id,this_date):
    headers = {
        'Content-Type': 'application/json',
        'n-token': token,
        'cookie': cookie,
    }
    response = requests.post('https://gw.newrank.cn/api/nrnavigation/nr/navigation/hotSpot/hotSpotIndex', headers=headers)

    if response.status_code != 200:
        return "failure"
    else:
        platform_map = {
            1: "快手热点",
            2: "抖音热点",
            5: "微博热点",
            6: "小红书热点",
            7: "百度热点",
            8: "B站热点",
            9: "知乎热点",
            10: "头条热点"
        }
        print("http newrank is ok.....")
        json_data = response.json()
        original_list = json_data['data']
        segments_data = {
            "segments": []
        }

        for item in original_list:
            # 提取热点内容信息
            nrAppHotSpotRankDtoList = item.get('nrAppHotSpotIndexDtoList', [])
            # 获取平台类型
            play_type = item.get('platform')
            platform_name = platform_map.get(play_type, f'未知平台({play_type})') if play_type is not None else ''

            segmentcontent = {
                "keyword": this_date+str(platform_name),
                "content": nrAppHotSpotRankDtoList
            }
            # 将内容转换为字符串格式
            content_str = json.dumps(segmentcontent, ensure_ascii=False) if segmentcontent else ""
            segment = {
                "content": content_str,
                "keywords": [this_date+str(platform_name)]
            }
            segments_data = {
                "segments": [segment]
            }

            url = "http://localhost:8088/v1/datasets/"+dataset_id+"/documents/"+document_id+"/segments"
            post_with_detailed_retry(url, difyheaders, segments_data)
        return "ok"

def update_document_segments(cookie,dataset_id, api_key,token):

    now = datetime.now()
    this_date = str(now.strftime('%Y-%m-%d'))
    hour = now.hour
    if hour > 18:
        period = "晚上-"
    elif hour > 14:
        period = "中午-"
    else:
        period = "早上-"
    this_date = str(this_date)+str(period)
    print(f"当前日期: {this_date}, 时间段: {period}")

    url = "http://localhost:8088/v1/datasets/"+dataset_id+"/document/create-by-text"
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }
    payload = {
        "name": this_date+"全网八大社交平台热点数据",
        "text": "",
        "indexing_technique": "high_quality",
        "doc_form": "text_model",
        "process_rule": {"mode": "automatic"}
    }
    response = requests.post(url, headers=headers, data=json.dumps(payload))
    json_data = response.json()
    print(f"[{datetime.now()}] 创建文档返回 数据: {json_data}")

    document_id =json_data['document']['id']
    print(f"document_id: {document_id}")
    time.sleep(5)
    newrankXhs_data = newrankXhs(cookie,token,headers,dataset_id,document_id,this_date)

    text_data = hotSpotIndex(cookie,token,headers,dataset_id,document_id,this_date)

    return "全部完成"


def post_with_detailed_retry(url, headers, text_data):
    print(f"[{datetime.now()}] 开始发送POST请求到: {url}")
    try:
        responsesegments = requests.post(
            url,
            headers=headers,
            data=json.dumps(text_data)
        )

        print(f"[{datetime.now()}] 返回状态码: {responsesegments.status_code}")

        # 如果不是404，成功返回
        if responsesegments.status_code != 404:
            print(f"[{datetime.now()}] 请求成功!")
    except Exception as e:
        print(f"[{datetime.now()}] 请求segments出现异常: {e}")
    return "ok"


if __name__ == "__main__":
    dataset_id = '${dataset_id}'
    api_key = '${api_key}'
    cookie = '${cookie}'
    token = '${token}'
    print("开始 getWxHotContent")
    response_data = update_document_segments(cookie,dataset_id, api_key,token)
    print("结束 getWxHotContent")